package com.study.controller;

import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.study.entity.db3.Role;
import com.study.entity.db3.dto.LoginDTO;
import com.study.service.db3.IAccountService;
import com.study.service.db3.IResourceService;
import com.study.util.treeutil.TreeNodeMap;

/**
 * 登录、登出 前端控制器
 * 
 * @author chenk
 *
 */
@Controller
@RequestMapping("/auth")
public class LoginController {

	@Autowired
	private IAccountService accountService;

	@Autowired
	private IResourceService resourceService;

	/**
	 * 用户登录
	 * 
	 * @param username
	 * @param password
	 * @param session
	 * @param attributes
	 * @param model
	 * @return
	 */
	@PostMapping("/login")
	public String login(String username, String password, HttpSession session, RedirectAttributes attributes,
			Model model) {
		LoginDTO loginDTO = accountService.login(username, password);
		String error = loginDTO.getError();
		if (!StringUtils.hasLength(error)) {
			session.setAttribute("account", loginDTO.getAccount());
			// 登录时，特殊处理和详情共用一个flag
			List<Role> roles = loginDTO.getAccount().getRoles();
			List<Long> roleIds = roles.stream().map(Role::getRoleId).collect(Collectors.toList());
			List<TreeNodeMap> resourceVOs = resourceService.listResource(roleIds, 1);
			model.addAttribute("resources", resourceVOs);

			// 将资源转换为代码模块名称的集合
			HashSet<String> module = resourceService.convert(resourceVOs);
			session.setAttribute("module", module);
		} else {
			attributes.addFlashAttribute("error", error);
		}
		return loginDTO.getPath();

	}

	/**
	 * 用户登出
	 * 
	 * @param session
	 * @return
	 */
	@GetMapping("/logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/";
	}
}
